#!/usr/bin/env python
# -*- coding:utf-- -*-
# __author__ = "liangpp"
# Date: 2023/1/6


from kubernetes import client, config
import re
import urllib3
from django.shortcuts import redirect
from k8sManage.models import ClusterInfo, KubeConfig

urllib3.disable_warnings()

# 登录认证
def login_auth(cluster_host=None, ca_file=None, token=None, kubeconfig=None):
    if token:
        configuration = client.Configuration()
        configuration.host = cluster_host  # APISERVER地址
        # ca_file = os.path.join(os.getcwd(), "ca.crt")  # K8s集群CA证书（/etc/kubernetes/pki/ca.crt）
        # configuration.ssl_ca_cert = ca_file
        configuration.verify_ssl = False  # 关闭证书验证，如果开启需要配置configuration.ssl_ca_cert
        token = token  # 获取token
        configuration.api_key = {"authorization": "Bearer " + token}
        client.Configuration.set_default(configuration)
    elif kubeconfig:
        kubeconfig = kubeconfig  # 获取kubeconfig文件
        import yaml
        yaml_kubeconfig = yaml.load(kubeconfig, Loader=yaml.FullLoader)  # 将yaml转为json
        config.load_kube_config_from_dict(yaml_kubeconfig)
    else:
        return {"code": 401, "msg": "认证失败！请检查token或kubeconfig文件"}

    # 验证权限
    try:
        core_api = client.CoreApi()
        if core_api.get_api_versions():
            res = {"code": 200, "msg": "登录成功！"}
        else:
            res = {"code": 403, "msg": "没有权限！"}
    except Exception as e:
        # print(e, type(e))
        e = str(e)
        result = re.search(r"\[\w+\s+\w+\]", e)
        if result:
            # msg = ((re.search(r"\[\w+\s+\w+\]", e)).group())
            res = {"code": 401, "msg": "集群连接失败！请检查集群状态"}
        else:
            res = {"code": 401, "msg": "认证失败！请检查token或kubeconfig文件"}
    return res


# 登录状态验证装饰器
def login_required(func):
    def inner(request):
        is_login = request.session.get("is_login", False)
        if is_login:
            return func(request)
        else:
            return redirect('/login')

    return inner


# 用于连接k8s api 获取数据
def conn_k8s_api(request, auth_type):
    if auth_type == "token":
        token = request.session.get("token", False)
        cluster_name = request.session.get("cluster_name", False)
        cluster_host = ClusterInfo.objects.get(cluster_name=cluster_name).cluster_address
        configuration = client.Configuration()
        configuration.host = cluster_host  # APISERVER地址
        # ca_file = os.path.join(os.getcwd(), "ca.crt")  # K8s集群CA证书（/etc/kubernetes/pki/ca.crt）
        # configuration.ssl_ca_cert = ca_file
        configuration.verify_ssl = False  # 关闭证书验证，如果开启需要配置configuration.ssl_ca_cert
        token = token  # 获取token
        configuration.api_key = {"authorization": "Bearer " + token}
        client.Configuration.set_default(configuration)
    elif auth_type == "kubeconfig":
        token = request.session.get("token", False)
        kubeconfig_text = KubeConfig.objects.get(cus_token=token).config_text  # 获取kubeconfig文件
        import yaml
        yaml_kubeconfig = yaml.load(kubeconfig_text, Loader=yaml.FullLoader)  # 将yaml转为json
        config.load_kube_config_from_dict(yaml_kubeconfig)


# 用于django channel 连接 k8s api
def channel_conn_k8s_api(auth_type, token, cluster_host):
    if auth_type == "token":
        token = token
        cluster_host = cluster_host
        configuration = client.Configuration()
        configuration.host = cluster_host  # APISERVER地址
        # ca_file = os.path.join(os.getcwd(), "ca.crt")  # K8s集群CA证书（/etc/kubernetes/pki/ca.crt）
        # configuration.ssl_ca_cert = ca_file
        configuration.verify_ssl = False  # 关闭证书验证，如果开启需要配置configuration.ssl_ca_cert
        configuration.api_key = {"authorization": "Bearer " + token}
        client.Configuration.set_default(configuration)
    elif auth_type == "kubeconfig":
        token = token
        kubeconfig_text = KubeConfig.objects.get(cus_token=token).config_text  # 获取kubeconfig文件
        import yaml
        yaml_kubeconfig = yaml.load(kubeconfig_text, Loader=yaml.FullLoader)  # 将yaml转为json
        config.load_kube_config_from_dict(yaml_kubeconfig)
